 package com.fizz.redpacket.algorithm;

 import java.util.ArrayList;
 import java.util.List;
 import java.util.Random;

public class DefaultAllocateStrategy implements AllocateStrategy {
     public List<String> allocate(int count, String moneyStr) {
        double money;
        if (count <= 0) {
            throw new RuntimeException("参数错误");
        }

        try {
             money = Double.parseDouble(moneyStr);
         } catch (Exception ex) {
        throw new RuntimeException("参数错误 money = " + moneyStr);
     }


     Random random = new Random();
     List<String> res = new ArrayList<>();
     double sum = money;
     double personCount = count;
     double randomMoney = sum / count;

     while (personCount > 1.0D) {
       randomMoney = random.nextDouble() * (sum / personCount - 0.01D) + 0.01D;
       personCount--;
       sum -= randomMoney;

       res.add(String.valueOf(randomMoney));
     }


     res.add(String.valueOf(randomMoney));
     return res;
   }


   public static void main(String[] args) {
     MyAllocateStrategy myAllocateStrategy = new MyAllocateStrategy();
     test(1, "2.3", (AllocateStrategy)myAllocateStrategy);
     test(3, "23", (AllocateStrategy)myAllocateStrategy);
     test(5, "123", (AllocateStrategy)myAllocateStrategy);
     test(100, "1", (AllocateStrategy)myAllocateStrategy);
     test(10, "1231321", (AllocateStrategy)myAllocateStrategy);
     test(100, "0.9", (AllocateStrategy)myAllocateStrategy);
     System.out.println(229.99999999999997D);
   }

   private static void test(int count, String money, AllocateStrategy defaultAllocateStrategy) {
     List<String> list = defaultAllocateStrategy.allocate(count, money);
     double sums = 0.0D;
     for (String each : list) {
       sums += Double.parseDouble(each);
     }

     System.out.println();
   }
 }

